#Implement the function given below and plot its two cycles. Plot its histogram also. f(t) = cost*cos5t + cos5t
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,2*np.pi, 1000)
y = np.cos(x)*np.cos(5*x) + np.cos(5*x)
plt.plot(x,y)
plt.show()
"""Implement the functions given below and plot two cycles of them. Plot scatter plot to
study their relationship.
f1(t) = sint
f2(t) = cost"""
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,2*np.pi, 1000)
y1= np.sin(x)
y2= np.cos(x)
plt.scatter(x,y1)
plt.scatter(x,y2)
plt.show()
"""Generate and plot the waveform given below and plot its histogram also. half wave recitifier"""
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,4,1000)
y = []
for i in x:
if np.sin(np.pi*i)>0:
y.append(np.sin(np.pi*i))
else:
y.append(0)
plt.plot(x,y)
plt.show()
"""Read the given csv file: ‘waveform2.csv’ as an array and plot it. Plot its histogram with an
appropriate bin size."""
import matplotlib.pyplot as plt #there was no download link so i just took the above problem and to depict saving in .csv file and reading from it
import numpy as np #I used the above problem
x = np.linspace(0,4,1000)
y = []
for i in x:
if np.sin(np.pi*i)>0:
y.append(np.sin(np.pi*i))
else:
y.append(0)
np.savetxt('waveform2.csv',[x,y], delimiter=',')
data=np.genfromtxt('waveform2.csv', delimiter=',')
plt.hist(data[1], bins=100)
plt.show()
"""Realize the function y=2+5sin(2πft) for f=1KHz and plot it. Write values of the function as a
csv file such that the sampling time should be the first value followed by its samples."""
import matplotlib.pyplot as plt
import numpy as np
import time
xmin=0
xmax=1
ymin=-4
ymax=7
plt.axis([xmin, xmax, ymin, ymax])
tic = time.process_time()
x = np.linspace(0,2*np.pi, 1000)
f = 1000 #Hz
y = 2 + 5*np.sin(2*np.pi*f*x)
plt.plot(x,y)
plt.show()
data=[f]
for i in y:
data.append(i)
toc = time.process_time()
data.insert(0,(toc-tic)*1000)
np.savetxt("functionSample.csv", data,delimiter=',')
print("Sampling time: ",(toc-tic)*1000) #time difference in milli seconds
Sampling time: 46.875
"""Write and execute a function to solve for the current transient through an RL network (with
R/L = 1) that is driven by the signal 5e^–t U(t). Plot the current through the circuit.
"""
"""
V(t) = RI + LdI/dt
dI/dt = V(t) - RI/L
"""
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import numpy as np
def model(y,t):
dydt = 5*np.exp(-t) - y
return dydt
RL = 1
R = 1
V = 5
i0 = V/R
t = np.linspace(0,20)
sol = odeint(model, i0, t)
plt.plot(t,sol)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0,100,1000)
w = np.pi/10
v = 5
for j in range(1,100):
v = v + (40/((2*j + 1)*np.pi)**2)*np.cos((2*j + 1)*w*t)
plt.plot(t, v)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
def model(y,t):
b = 0.05
m=0.01
L = 0.5
g = 9.8
y,z = y
dydx = [z,(-b/m)*z + -(g/L)*np.sin(y)]
return dydx
t = np.linspace(0,5,100)
sol = odeint(model, [0,3], t)
plt.plot(t,sol[:,0])
plt.show()
"""Plot a sinc function from time t = -10 to 10 and plot its histogram also"""
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(-10,10,1000)
y = np.sinc(t)
plt.plot(t,y)
plt.show()
plt.hist(y,bins=100)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
T = int(input('enter a number'))
t = np.linspace(0,10,100)
y = []
for i in t:
temp = 0
for j in range(1,200,2):
temp = temp + (1/j)*(np.sin((j*np.pi*i)/T))
temp = temp * (4/np.pi)
y.append(temp)
plt.plot(t,y)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(-10,10,100)
y = []
for i in t:
if i >= -5 and i <= 5:
y.append(4*(t**2))
else:
y.append(100)
plt.boxplot(y,showmeans=True)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
def model(y,x):
y,z = y
dydx = [z,-0.5*z - 7]
return dydx
i0 = [21,12]
x = np.arange(0,5,0.5)
sol = odeint(model, i0, x)
plt.plot(x,sol[:,0])
plt.show()
plt.stem(x,sol[:,0])
plt.show()
"""Given a series circuit consisting of a series circuit consisting of a device which has an
inductance of 1 H ,resistance of 22 Ώ and a a capacitor of 200µF and an input voltage of 12 V
DC .If the initial charge and current are both zero, write a program to plot the charge and
current at the time t= 0 to 10s."""
"""
L dI2/d2t + R dI/dt + 1/c I = V'
"""
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
L = 1
R = 22
C = 200e-6
V = 12
def model(i,t):
i,z = i
didt = [z/L,-(R*z) - i/(C)]
return didt
i0 = [V/R,0]
t = np.linspace(0,10,100)
sol = odeint(model, i0, t)
plt.plot(t, sol[:,0])
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
def model(T,t):
k=-0.55
Ts = 25
return (k)*(T-Ts)
t = np.arange(0,12*60)
t0 = 60
sol = odeint(model, t0, t)
plt.plot(t,sol)
plt.show()
""""7. Implement the function given below and plot its two cycles. Plot its box plot also and
write down the mean and third quartile value.
f(t) = 3+ sin3t+sin5t"""
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0,2*np.pi, 100)
f = []
for i in t:
f.append(3+np.sin(3*i)+np.sin(5*i))
plt.boxplot(f,showmeans=True)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
"""
half life T = ln 2 / λ
"""
def model(N,t):
return -np.log(2)*N/(5)
i0 = 600
t = np.linspace(0,100, 10000) # days
sol = odeint(model, i0, t)
plt.ylabel('Bismuth (mg)')
plt.xlabel('Time (days)')
plt.plot(t,sol[:,0])
plt.show()
import matplotlib.pyplot as plt
import numpy as np
f1 = []
f2 = []
x = np.linspace(0,100,100)
L = 20
for i in x:
temp = 0
for j in range(1,20,2):
temp = temp + ((-1)**((j-1)/2)/(j**2))*np.sin((j*np.pi*i)/L)
temp = temp * (8/np.pi)
f1.append(temp)
temp = 0
for j in range(1,100,2):
temp = temp + ((-1)**((j-1)/2)/(j**2))*np.sin((j*np.pi*i)/L)
temp = temp * (8/np.pi)
f2.append(temp)
plt.plot(x,f1)
plt.plot(x,f2)
plt.show()
ap, cp, wp = 26.2, 21, 10.1
ac, cc, wc = 40.2, 44.8, 14.3
af, cf, wf = 71.2, 63.5, 82.8
print("Amount of proteins in mixture 1: ", 26.2*6+21*3+10.1*1)
print("Amount of proteins in mixture 2: ", 26.2*3+21*6+10.1*1)
print("Amount of proteins in mixture 3: ", 26.2*3+21*1+10.1*6)
print("Amount of carbohydates in mixture 1: ",40.2*6+44.8*3+14.3*1)
print("Amount of carbohydates in mixture 2: ",40.2*3+44.8*6+14.3*1)
print("Amount of carbohydates in mixture 3: ",40.2*3+44.8*1+14.3*6)
print("Amount of Fat in mixture 1: ", 71.2*6+63.5*3+82.8*1)
print("Amount of Fat in mixture 1: ", 71.2*3+63.5*6+82.8*1)
print("Amount of Fat in mixture 1: ", 71.2*3+63.5*1+82.8*6)
Amount of proteins in mixture 1: 230.29999999999998 Amount of proteins in mixture 2: 214.7 Amount of proteins in mixture 3: 160.2 Amount of carbohydates in mixture 1: 389.90000000000003 Amount of carbohydates in mixture 2: 403.7 Amount of carbohydates in mixture 3: 251.20000000000002 Amount of Fat in mixture 1: 700.5 Amount of Fat in mixture 1: 677.4 Amount of Fat in mixture 1: 773.9
import numpy as np
A = np.array([[1,2,3,4,5],[0,2,3,4,5],[0,0,3,4,5],[0,0,0,4,5],[0,0,0,0,5]])
w, v = np.linalg.eig(A)
print("Eigen Values are", w)
print("A^2: ", A.dot(A))
Eigen Values are [1. 2. 3. 4. 5.] A^2: [[ 1 6 18 40 75] [ 0 4 15 36 70] [ 0 0 9 28 60] [ 0 0 0 16 45] [ 0 0 0 0 25]]
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1,40,1)
y = []
big = 0
for i in x:
if i%10==0:
big = i
if i>big and i<big+10:
if big%20==0:
y.append(5)
else:
y.append(0)
else:
y.append(0)
plt.plot(x,y)
plt.show()
import numpy as np
A = [[2,1,1],[1,3,2],[2,1,2]]
"""
each column has the number of hours put in by a particular product in machine of that column number
or in other words
each row is the sum of product of time required by the product in that machine and the total number of products
amounting to fully utilize the total time of that machine, i.e. the result of the sum
"""
B = [3*60, 5*60, 4*60]
solution = np.linalg.solve(A,B)
print("A Type: ",solution[0])
print("B Type: ",solution[1])
print("C Type: ",solution[2])
A Type: 36.0 B Type: 48.0 C Type: 60.0
import numpy as np
from sympy import Symbol
t = Symbol('t')
s = 3*t**4 - 40*t**3 + 126*t**2 -9
v = s.diff(t)
a = s.diff(t,2)
print("Velocity at instant 0: ",v.subs(t,0))
print("Velocity at instant 3: ",v.subs(t,3))
print("Velocity at instant 5: ",v.subs(t,5))
print("Velocity at instant 7: ",v.subs(t,7))
print("Velocity at instant 10: ",v.subs(t,10))
print("Acceleration at instant 0: ",a.subs(t,0))
print("Acceleration at instant 3: ",a.subs(t,3))
print("Acceleration at instant 5: ",a.subs(t,5))
print("Acceleration at instant 7: ",a.subs(t,7))
print("Acceleration at instant 10: ",a.subs(t,10))
Velocity at instant 0: 0 Velocity at instant 3: 0 Velocity at instant 5: -240 Velocity at instant 7: 0 Velocity at instant 10: 2520 Acceleration at instant 0: 252 Acceleration at instant 3: -144 Acceleration at instant 5: -48 Acceleration at instant 7: 336 Acceleration at instant 10: 1452
"""
After t seconds an object is moving at a speed of te-t/2 . Write a program to find the distance
travelled by the object at t=0,10 and 100s"""
import numpy as np
from scipy.integrate import quad
import matplotlib.pyplot as plt
def func(t):
return t*np.exp(-t/2)
print("Distance travelled at time t = 0s :", quad(func,0,0)[0])
print("Distance travelled at time t = 10s :", quad(func,0,10)[0])
print("Distance travelled at time t = 100s :", quad(func,0,100)[0])
#extras
t = np.linspace(0,100,100)
d = []
v = t*np.exp(-t/2)
for i in t:
d.append(quad(func,0,i)[0])
plt.plot(t,d)
plt.plot(t,v)
plt.legend(['distance/time','velocity/time'])
plt.show()
Distance travelled at time t = 0s : 0.0 Distance travelled at time t = 10s : 3.8382892720219486 Distance travelled at time t = 100s : 4.0
import numpy as np
A = np.array([[1,1,0,1],[0,0,0,1],[1,1,0,0]])
At = np.transpose(A)
print('A*At: ',A.dot(At))
s,v,d = np.linalg.svd(A)
print("S: ",s)
print("V: ",v)
print("D: ",d)
A*At: [[3 1 2] [1 1 0] [2 0 2]] S: [[ 0.78867513 0.21132487 0.57735027] [ 0.21132487 0.78867513 -0.57735027] [ 0.57735027 -0.57735027 -0.57735027]] V: [2.17532775e+00 1.12603250e+00 5.73316705e-17] D: [[ 6.27963030e-01 6.27963030e-01 0.00000000e+00 4.59700843e-01] [-3.25057584e-01 -3.25057584e-01 0.00000000e+00 8.88073834e-01] [ 7.07106781e-01 -7.07106781e-01 0.00000000e+00 -2.77555756e-16] [ 0.00000000e+00 0.00000000e+00 1.00000000e+00 0.00000000e+00]]
"""
A capacitor in an RC circuit with R = 5 KΩ and C = 1 µF is excited with a 2sin(200t) voltage
Write a program to plot the current response of the circuit."""
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
"""
dI/dt = dV/dt - (I/RC)
"""
def model(y,t):
R = 5000
C = 10e-6
return 400*np.cos(200*t) - y/(R*C)
i0 = 0
t = np.linspace(0,1,100)
sol = odeint(model, i0,t)
plt.plot(t,sol[:,0])
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,100,100)
L = 20
f1 = []
f2 = []
f3 = []
for i in x:
temp = 0
for j in range(1,2,2):
temp = temp + ((-1)**((j-1)/2)/(j**2))*np.sin((j*np.pi*i)/L)
f1.append(temp* (8/np.pi))
temp = 0
for j in range(1,4,2):
temp = temp + ((-1)**((j-1)/2)/(j**2))*np.sin((j*np.pi*i)/L)
f2.append(temp* (8/np.pi))
temp = 0
for j in range(1,6,2):
temp = temp + ((-1)**((j-1)/2)/(j**2))*np.sin((j*np.pi*i)/L)
f3.append(temp* (8/np.pi))
fig,a = plt.subplots(3,1)
a[0].plot(x,f1)
a[1].plot(x,f2)
a[2].plot(x,f3)
plt.show()
import matplotlib.pyplot as plt
x0 = 2.38
t = np.linspace(0,15,100)
data = []
temp = x0
for i in t:
temp = temp + 1 + (1/((1+i)**2))
data.append(temp)
plt.plot(t,data)
plt.xlabel('time in years')
plt.ylabel('height of tree in m')
plt.show()
"""
Given the equation for damped simple harmonic motion
y′′+2y′+2y=cos(2x), y(0)=0,y′(0)=0.Write a program to solve this."""
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot
def model(y,x):
y,z = y
return [z,np.cos(2*x)-2*z-2*y]
y0 = [0,0]
x = np.linspace(0,100,1000)
sol = odeint(model, y0, x)
plt.plot(x,sol[:,0])
plt.show()
x = 0.25
sum1 = 0
for i in range(100):
sum1 = sum1 + x**i
print("1/ 1-x for x = 0.25: ",sum1)
1/ 1-x for x = 0.25: 1.3333333333333333
"""
Write a program to plot the Lissajous pattern of a sine wave and its derivative"""
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,2,1000)
d = float(input('enter phase difference: '))
X = []
Y = []
for i in x:
X.append(np.sin(i*np.pi))
Y.append(np.sin(i*np.pi + d*np.pi/180))
plt.plot(X,Y)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,4,1000)
y = []
for i in x:
y.append(abs(np.sin(np.pi*i)))
plt.plot(x,y)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
x = [22,87,5,43,56,73,55,54,11,0,51,5,79,31,27]
print('mean: ', np.mean(x))
print('25th percentile: ',np.percentile(x,25))
plt.hist(x,bins=(50))
plt.show()
mean: 39.93333333333333 25th percentile: 16.5
"""
Implement the function given below and plot its two cycles. Plot its histogram also.
f(t) = sin(πt) + sin(3πt)"""
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,10,1000)
f = []
for i in x:
f.append(np.sin(np.pi*i) + np.sin(3*np.pi*i))
plt.plot(x,f)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
def model(y,t):
b = 0.05
m = 2
L = 1
g = 9.8
y,z = y
dydx = [z,(-b/m)*z + -(g/L)*np.sin(y)]
return dydx
t = np.linspace(0,5,100)
sol = odeint(model, [0,3], t)
plt.plot(t,sol[:,0])
plt.show()
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0,20,10000)
f = []
for i in t:
temp = 0
for j in range(2,201,2):
temp = temp + (1/j)*np.sin(j*np.pi*i/20)
temp *= 4/np.pi
f.append(1+temp)
plt.plot(t,f)
plt.show()
"""
Implement the functions given below and plot at least two cycles of them. Plot scatter
plot to study their relationship.
f1(t) = cos3πt
f2(t) = cos5πt
"""
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0,2,100)
f1 = np.cos(3*np.pi*t)
f2 = np.cos(5*np.pi*t)
fig,a = plt.subplots(3,1)
a[0].plot(t,f1)
a[1].plot(t,f2)
a[2].scatter(t,f1)
a[2].scatter(t,f2)
plt.show()
"""Write a program to plot the Lissajous pattern of two sine waves of different frequencies."""
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,2,1000)
a = float(input("input a:"))
b = float(input("input b:"))
d = float(input('enter phase difference: '))
X = []
Y = []
for i in t:
X.append(np.sin(a*i*np.pi))
Y.append(np.sin(b*i*np.pi + d*np.pi/180))
plt.plot(X,Y)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0,40,0.4)
y=[]
big=0
for i in x:
if i%10==0:
y.append(0)
big = i
else:
y.append(i/2 - big/2)
plt.plot(x,y)
plt.show()
"""Realize the function y=2+sin(t/2) and plot its 3 complete cycles. Write values of the function
as a csv file such that the sampling time should be the first value followed by its samples."""
import matplotlib.pyplot as plt
import numpy as np
import time
tic = time.process_time()
x = np.linspace(0,6*np.pi,100)
y = 2 + np.sin(x/2)
plt.plot(x,y)
plt.show()
x = list(x)
x.insert(0,0)
y = list(y)
data = [x,y]
toc = time.process_time()
data[1].insert(0,(toc-tic)*1000)
# print(data)
np.savetxt("function_sin.csv",data,delimiter = ',')
# this process have done to have equal length of arrays inside data so the csv file would have
# two columns of equal length and in this case, the first row would contain 0, sampling_time_value
# can't enter string so instead of 'sampling time' i put 0
"""Starting from rest, a particle moving in a straight line has an acceleration of a = (2t - 6) m/s2
,
where t is in seconds. Write a program to the particle’s velocity and position. Find the
velocity when t = 6 s, and what is its position when t = 11 s?"""
import numpy as np
import sympy as sym
t = sym.Symbol('t')
a = 2*t - 6
v = a.integrate(t)
d = v.integrate(t)
print("Velocity: ",v)
print("Distance: ",d)
v6 = v.subs(t,6)
print("Velocity at 6s: ",v6)
d11 = d.subs(t,11)
print("Position at 11s: ",d11)
Velocity: t**2 - 6*t Distance: t**3/3 - 3*t**2 Velocity at 6s: 0 Position at 11s: 242/3
"""Plot a sinc function from time t = 0 to 7. Plot its box plot also and write down the
mean value and first quartile value."""
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,7,100)
y = np.sinc(x*np.pi/180)
print("Mean: ",np.mean(y))
print("First quartile (25): ",np.percentile(y,25))
plt.boxplot(y,showmeans=(True))
plt.show()
Mean: 0.991811057140368 First quartile (25): 0.9862457560117849
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0,2*np.pi,100)
v = [[5]*len(t)]
w = np.pi/10
for i in range(1,3):
temp = []
for j in t:
temp.append((40/(((2*i + 1)*np.pi)**2))*np.cos(w*(2*i + 1)*j))
v.append(temp)
plt.plot(t,v[0])
plt.plot(t,v[1])
plt.plot(t,v[2])
plt.legend(['first term','second term','third term','sum of the terms'])
plt.plot(t,np.add(np.add(v[0],v[1]),v[2]))
plt.show()
"""
f(t) = t ,for t= -5 to 5
= 10-t ,for t=5 to 15
= 0 , otherwise
Plot f(t) forthe vectort = *−5, 15+."""
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(-20,20,100)
y = []
for i in t:
if i>= -5 and i<5:
y.append(i)
elif i>=5 and i<15:
y.append(10-i)
else:
y.append(0)
plt.plot(t,y)
plt.show()
"""
A souvenir shop sells Hat, T shirt and Jackets. 3 hats, 2 T shirts and 1 jacket cost Rs. 140. 2
hats, 2 T shirts and 2 jackets cost Rs. 170. 1 hat, 3 T shirts and 2 jackets cost Rs. 180.
program to find the cost of individual items"""
import numpy as np
A = [[3,2,1],[2,2,2],[1,3,2]]
B = [140,170,180]
sol = np.linalg.solve(A,B)
print("cost of hat", round(sol[0]))
print("cost of tshirt",round(sol[1]))
print("cost of jacket",round(sol[1]))
cost of hat 15 cost of tshirt 25 cost of jacket 25
import numpy as np
#did not know the sign of z in theird equation
A = [[2,-1,1,-2],[2,2,-3,1],[1,1,1,0],[4,-3,2,-3]]
B =[-5,-1,-1,-8]
sol = np.linalg.solve(A,B)
print("Solution:",sol)
A = [[2,-1,1,-2],[2,2,-3,1],[1,1,-1,0],[4,-3,2,-3]]
sol = np.linalg.solve(A,B)
print("Solution:",sol)
Solution: [-0.92307692 -0.23076923 0.15384615 1.76923077] Solution: [1.11022302e-16 1.00000000e+00 2.00000000e+00 3.00000000e+00]
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
"""
half life T = ln 2 / λ
"""
def model(N,t):
return -np.log(2)*N/5730
i0 = 1000
t = np.linspace(0,2000, 10000) # years
sol = odeint(model, i0, t)
plt.ylabel('Carbon (g)')
plt.xlabel('Time (years)')
plt.plot(t,sol[:,0])
plt.show()
"""
Implement the function given below and plot its two cycles. Plot its box plot also and
write down the mean and thrid quartile value
f(t) = 3+ cos(3πt)+sin(5πt)"""
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0,3,100)
f = 3 + np.cos(3*np.pi*t) + np.sin(5*np.pi*t)
print("Mean: ",np.mean(f))
print("Third quartile value:",np.quantile(f,0.75)) # we can also use np.percentile() for this but we give 75 instead of 0.75
plt.plot(t,f)
plt.show()
Mean: 3.041220561427445 Third quartile value: 3.829496730050256
import sympy as sym
from scipy.integrate import quad
t = sym.Symbol('t')
v = 12 - 3*(t**2)
d = v.integrate(t)
a = v.diff(t) # change in velocity
k = a.diff(t) # change in acceleration
print("Acceration when t = 4: ",a.subs(t,4))
def model(t):
return 12 - 3*(t**2)
print("displacement from t = 0 to t = 10",round(quad(model,0,10)[0]))
print("distance from t=0 to t=10",d.subs(t,10)-d.subs(t,0))
Acceration when t = 4: -24 displacement from t = 0 to t = 10 -880 distance from t=0 to t=10 -880
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0,40,1)
y=[]
big=0
for i in x:
if i%10==0:
y.append(0)
big = i
elif i>big and i <big+10 and (big+10)%20==0:
y.append(0)
else:
y.append(i/2 - big/2)
plt.plot(x,y)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
t = np.linspace(0,20,100)
k = float(input('enter constant')) # graph depends on k value
def model(v,t):
return -k*v
v0 = 10
sol = odeint(model,v0,t)
plt.plot(t,sol)
plt.show()
"""For cooling, rhs is always negative, refer https://web.math.ucsb.edu/~myoshi/cooling.pdf"""
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
def model(T,t):
k= -0.1
Ts = 27
return k*(T-Ts)
t = np.arange(0,10,1)
t0 = 52
sol = odeint(model, t0, t)
plt.plot(t,sol)
plt.show()
import numpy as np
A = np.array([[1,3,5],[1,1,0],[1,1,2],[1,3,3]])
s,v,d = np.linalg.svd(A)
print("S,V,D are",s,v,d,sep='\n')
At = A.transpose()
print("AAt: ",A.dot(At))
S,V,D are [[-7.63546975e-01 -4.08248290e-01 1.81479992e-02 -5.00000000e-01] [-1.02727662e-01 8.16496581e-01 2.69778355e-01 -5.00000000e-01] [-3.08182987e-01 -1.38777878e-16 8.09335064e-01 5.00000000e-01] [-5.58091650e-01 4.08248290e-01 -5.21408710e-01 5.00000000e-01]] [7.71115035 1.41421356 0.73359408] [[-0.22468104 -0.56746741 -0.79214845] [ 0.57735027 0.57735027 -0.57735027] [ 0.78497458 -0.58706678 0.1979078 ]] AAt: [[35 4 14 25] [ 4 2 2 4] [14 2 6 10] [25 4 10 19]]
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0,100,10000)
f = (100-t)*np.sin(t)
plt.plot(t,f)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(1,40)
y=[]
big=0
for i in x:
if i%10==0:
y.append(-1)
big = i
elif i>big and i <big+10 and (big+10)%20==0:
y.append(-1)
else:
y.append(1)
plt.plot(x,y)
plt.show()
import numpy as np
def function():
z = int(input('enter number of equations'))
print("enter {} numbers".format(z*z))
entries=list(map(int,input('input numbers with space in between: ').split()))
if len(entries) == z*z:
matrix = np.array(entries).reshape(z,z)
print("Equation matrix:",matrix)
temp = list(map(int,input('Enter numbers with space in middle: ').split()))
if len(temp) ==z:
B = np.array(temp)
print("Coefficient matrix: ",B)
else:
print("Entered, wrong number of elements")
print("Try again")
function()
else:
print("Can't reshape as rows*columns does not match total input")
print("Try again")
function()
det = np.linalg.det(matrix)
if det != 0 :
sol = np.linalg.solve(matrix,B)
for i in range(z):
print("Solution in the order of variables entered: ",sol[i])
else:
print("Determinant is 0, try again")
function()
enter 4 numbers
Equation matrix: [[2 1] [3 4]]
Coefficient matrix: [10 20] Solution in the order of variables entered: 4.000000000000001 Solution in the order of variables entered: 1.9999999999999996
"""Write a program to implement a simple calculator."""
def calculate():
operation = input('''
Please type in the math operation you would like to complete:\n
+ for addition\n
- for subtraction\n
* for multiplication\n
/ for division\n
% for modulo \n
// for integer division
''')
x = int(input('Please enter the first number: '))
y = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(x, y))
print(x + y)
elif operation == '-':
print('{} - {} = '.format(x, y))
print(x - y)
elif operation == '*':
print('{} * {} = '.format(x, y))
print(x * y)
elif operation == '/':
print('{} / {} = '.format(x, y))
print(x / y)
elif operation == '%':
print('{} % {} = '.format(x, y))
print(x % y)
elif operation == '//':
print('{} // {} = '.format(x, y))
print(x // y)
else:
print('You have not typed a valid operator, please run the program again.')
# Call calculate() outside of the function
calculate()
3 + 2 = 5
x = 0.25
sum1 = 1
for i in range(1,100):
sum1 = sum1 + x**i
print("result =",sum1)
lhs = 1/(1-x)
rhs = sum1
if lhs == rhs:
print("LHS = RHS")
else:
print("lhs != RHS")
result = 1.3333333333333333 LHS = RHS
""".Write a program to find the Harmonic Series up to N terms and Sum of those N terms. Read a
and N through Key board."""
a = int(input('Enter A: '))
d = int(input('Enter D:'))
n = int(input('Enter number of terms: '))
data = []
for i in range(n):
print("Term {}: ".format(i+1),1/(a+(i*d)))
data.append(1/(a+(i*d)))
print("sum of terms: ", sum(data))
Term 1: 0.5 Term 2: 0.2 sum of terms: 0.7
import numpy as np
Is =1.17e-9 # reverse saturation current
Vd = 0.4 # voltage across diode, applied in forward bias
Vt = 25.2e-3 #thermal voltae
n = 1 #assuming quality factor to be 1
Id = Is*(np.exp(Vd/(n*Vt))-1)
print("Forward bias current: ",Id)
Forward bias current: 0.009156911378647114
data = {'Captain Marvel': 'Apple', 'Thor':'Sun', 'Hulk':'Pot','Doctor Strange': 'Van'}
vote = ['Pot', 'Van', 'Pot', 'Sun', 'Apple', 'Sun', 'Apple', 'Van', 'Van', 'Apple', 'Pot', 'Sun', 'Apple', 'Van', 'Apple',
'Apple']
for i in data:
print("Candidate: ",data[i])
print("Votes are ",vote)
results = {}
for i in vote:
if i in vote and i not in results:
for j in data:
if data[j]==i:
keyd = j
results[keyd] = vote.count(i)
print(results)
votes = 0
winner = ''
for i in results:
if results[i]>votes:
votes = results[i]
winner = i
print('the Winner is',winner,'by',votes,'votes')
Candidate: Apple
Candidate: Sun
Candidate: Pot
Candidate: Van
Votes are ['Pot', 'Van', 'Pot', 'Sun', 'Apple', 'Sun', 'Apple', 'Van', 'Van', 'Apple', 'Pot', 'Sun', 'Apple', 'Van', 'Apple', 'Apple']
{'Hulk': 3, 'Doctor Strange': 4, 'Thor': 3, 'Captain Marvel': 6}
the Winner is Captain Marvel by 6 votes
Square wave
'''Generate the following signals : square wave, ramp, unit step, impulse'''
import numpy as np
import matplotlib.pyplot as plt
f = 1000
w = 2*np.pi*f
t = np.linspace(0,4*np.pi,100)
sq1 = []
n = 100
'''square wave'''
temp = 0
#assuming a 100 terms
for j in range(n):
temp = temp + ((1/(2*j + 1))*np.sin((2*j + 1)*w*t))
sq1.append((4/np.pi)*temp)
plt.plot(t,sq1[0])
plt.title("Square waves")
plt.show()
'''ramp signal'''
rs2 = n * t/10
plt.plot(t,rs2)
plt.title('ramp signal')
plt.show()
'''unit step'''
us1 = [0]
for i in range(1,len(t)):
us1.append(n/100)
plt.plot(t,us1)
plt.title('unit step signal')
plt.show()
'''impulse function'''
us1 = [n/100]
for i in range(1,len(t)):
us1.append(0)
plt.plot(t,us1)
plt.title('unit impulse signal')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def model(p,t):
return 0.1823*p
p0 = 200000
t = np.linspace(0,40,100)
sol = odeint(model, p0,t)
plt.plot(t+2000,sol)
plt.show()
"""Write a program to find the area and perimeter of triangle/ rhombus / square, trapezium."""
def triangle(s1,s2,s3):
s = (s1+s2+s3)*0.5
return [(s*(s-s1)*(s-s2)*(s-s3))**0.5, s*2]
def rhombus(d1,d2):
return [d1*d2*0.5, 2*((d1**2 + d2**2)**0.5)]
def square(s):
return [s*s, 4*s]
def trapezium(a,b,c,d,h):
return [(a+b)*h/2, a+b+c+d]
'''Write a program to interchange the row and columns of a matrix f the no. of rows and
column are equal.'''
x=int(input('enter number of rows for matrix: '))
y=int(input('enter number of columns for matrix: '))
entries=list(map(int,input('input number with space in between: ').split()))
if len(entries) == x*y:
matrix = np.array(entries).reshape(x,y)
matrix_t = np.zeros((y,x))
for i in range(y):
for j in range(x):
matrix_t[i][j] = matrix[j][i]
print('old matrix: ',matrix)
print('new matrix: ',matrix_t)
old matrix: [[1 2 3] [4 5 6]] new matrix: [[1. 4.] [2. 5.] [3. 6.]]
'''A second hand car dealer needs the information regarding car in the form of a python
dictionary. The information should include Name of Car, Registration No. ,Colour, .Create
or at least five different cars. After creating the dictionary, delete one row, (not the first
and last) add the following in an that row .
Benz-S Class, KL 37S4321, 2015, 30,000 KM Black'''
data = [
{'name':'lambo ','regn no':'KL 47 BT 0000','year':2011,'kilometers':10000,'color':'black'},
{'name':'ferrari','regn no':'KL 47 BT 1111','year':2012,'kilometers':10000,'color':'black'},
{'name':'pagani ','regn no':'KL 47 BT 2222','year':2013,'kilometers':10000,'color':'black'},
{'name':'bugatti','regn no':'KL 47 BT 3333','year':2014,'kilometers':10000,'color':'black'},
{'name':'hyundai','regn no':'KL 47 BT 4444','year':2015,'kilometers':10000,'color':'black'},]
print(data)
for i in data:
if data.index(i) != len(data) -1 or data.index(i)!=0:
data[data.index(i)]['name'] = 'Benz-S Class'
data[data.index(i)]['regn no'] = 'KL 37S432'
data[data.index(i)]['year'] = 2015
data[data.index(i)]['kilometers'] = 30000
data[data.index(i)]['color'] = 'Black'
print(data)
[{'name': 'lambo ', 'regn no': 'KL 47 BT 0000', 'year': 2011, 'kilometers': 10000, 'color': 'black'}, {'name': 'ferrari', 'regn no': 'KL 47 BT 1111', 'year': 2012, 'kilometers': 10000, 'color': 'black'}, {'name': 'pagani ', 'regn no': 'KL 47 BT 2222', 'year': 2013, 'kilometers': 10000, 'color': 'black'}, {'name': 'bugatti', 'regn no': 'KL 47 BT 3333', 'year': 2014, 'kilometers': 10000, 'color': 'black'}, {'name': 'hyundai', 'regn no': 'KL 47 BT 4444', 'year': 2015, 'kilometers': 10000, 'color': 'black'}]
[{'name': 'Benz-S Class', 'regn no': 'KL 37S432', 'year': 2015, 'kilometers': 30000, 'color': 'Black'}, {'name': 'Benz-S Class', 'regn no': 'KL 37S432', 'year': 2015, 'kilometers': 30000, 'color': 'Black'}, {'name': 'Benz-S Class', 'regn no': 'KL 37S432', 'year': 2015, 'kilometers': 30000, 'color': 'Black'}, {'name': 'Benz-S Class', 'regn no': 'KL 37S432', 'year': 2015, 'kilometers': 30000, 'color': 'Black'}, {'name': 'Benz-S Class', 'regn no': 'KL 37S432', 'year': 2015, 'kilometers': 30000, 'color': 'Black'}]